<!-- 文件切片上传+请求线程数 -->
<template>
    <div class="file-slice">
        <input type="file" ref="inputRef" @change="changeInput">
    </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue';

const inputRef = ref(); // input组件实例
const chunk_size = ref(1024 * 1024 * 5); // 每个分片大小5M
const Thread_Count = navigator.hardwareConcurrency || 4; // 得到计算机的总线程数

/**
 * input选择文件时
 */
const changeInput = async (e: any) => {
    const file = e.target?.files[0];
    console.time('开始时间');
    const chunks = await changecutFile(file);
    console.timeEnd('结束时间');
    console.log(chunks, 'chunks');
    console.log('Thread_Count', Thread_Count);

}

/**
 * 分片
 * @param {any} file 文件对象
 * @returns 返回总分片结果
 */
const changecutFile = async (file: any) => {
    return new Promise((resolve) => {
        const chunkCount = Math.ceil(file.size / chunk_size.value); // 得到总分片的数量（比如一个文件100M然后除于每片5M得到总分片的数量，向上取整，如6.5个分片，就取7，因为没有0.5个分片）
        const threadChunkCount = Math.ceil(chunkCount / Thread_Count); // 每个线程需要分到的分片数量
        let result: any = [];
        let finishCount = 0; // 计数,控制线程结束
        for (let i = 0; i < Thread_Count; i++) {
            let start = i * threadChunkCount;
            let end = Math.min(start * threadChunkCount, chunkCount)
            // 开启一个线程任务
            const worker = new Worker('../../../public/FileThread/index.js', {
                type: 'module',
            });
            worker.postMessage({ // 给线程发消息
                file,
                start, // 从哪个分片开始
                end, // 哪个分片结束
                chunk_size: chunk_size.value
            });
            worker.onmessage = (e: any) => {
                worker.terminate();
                result[i] = e.data;
                finishCount++;
                if (finishCount == Thread_Count) {
                    resolve(result.flat())
                }
            }
        }
    })
}

</script>

<style lang="scss" scoped></style>